package com.wnxy.admin.common.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rabbitmq.client.Channel;
import com.wnxy.admin.common.handler.ChargingPileStateEnum;
import com.wnxy.admin.common.handler.ReservationEnum;
import com.wnxy.admin.entity.Reservation;
import com.wnxy.admin.service.IChargingPileService;
import com.wnxy.admin.service.ICustomerService;
import com.wnxy.admin.service.IReservationService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author LQC
 * @note 取消预约延迟队列监听器
 */

@Component
@RabbitListener(queues = {"reservationQueue"})
public class ReservationListener {
    private final IReservationService reservationServiceImpl;
    private final IChargingPileService chargingPileServiceImpl;
    private final ICustomerService customerServiceImpl;

    public ReservationListener(IReservationService reservationServiceImpl, IChargingPileService chargingPileServiceImpl, ICustomerService customerServiceImpl) {
        this.reservationServiceImpl = reservationServiceImpl;
        this.chargingPileServiceImpl = chargingPileServiceImpl;
        this.customerServiceImpl = customerServiceImpl;
    }

    @RabbitHandler
    public void handlerMsg(Long orderId, Channel channel,
                           @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        try {

            Reservation dbReservation = reservationServiceImpl.getOne(Wrappers.lambdaQuery(Reservation.class)
                    .eq(Reservation::getOrdernum, orderId));

            //如果订单号状态为预约中，则更改预约状态为取消

            if (dbReservation.getState() == ReservationEnum.APPOINTMENT_IN_PROGRESS.getCode()) {
                reservationServiceImpl.update(Wrappers.lambdaUpdate(Reservation.class)
                        .eq(Reservation::getOrdernum, orderId).set(Reservation::getState, ReservationEnum.CANCELED.getCode()));


                // TODO: 2023/12/2 修改电桩状态为正常
                Long chargingId = Long.valueOf(dbReservation.getChargingId());
                chargingPileServiceImpl.updatePileStateById(chargingId, ChargingPileStateEnum.PIE_DEFAULT.getCode());

                // TODO: 2023/12/2修改客户状态为正常
                dbReservation.setState(2);
                customerServiceImpl.editService(dbReservation, 0);
            }
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, true, false);
        }


    }
}
